﻿using System;
using RpcClient.Interface;
using RpcHelper;
using RpcModel;

namespace RpcClient.Tran.Tcc
{
    /// <summary>
    /// Tcc事务摸版
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="Extend"></typeparam>
    internal class TccBasicTemplate<T, Extend> : ITranTemplate where T : class
    {
        private readonly IUnityCollect _Unity = null;
        private readonly Type _Type = null;
        private readonly bool _IsBasicType = false;
        private readonly Extend _def = default;
        public TccBasicTemplate(string name)
        {
            this.TranMode = RpcTranMode.Tcc;
            this._Type = typeof(Extend);
            this._IsBasicType = Tools.IsBasicType(this._Type);
            this.TranName = name;
            this._Unity = RpcClient.Unity;
        }
        /// <summary>
        /// 事务名
        /// </summary>
        public string TranName
        {
            get;
        }
        /// <summary>
        /// 事务执行方式
        /// </summary>
        public RpcTranMode TranMode
        {
            get;
            set;
        } = RpcTranMode.Tcc;
        /// <summary>
        /// 提交事务
        /// </summary>
        /// <param name="json"></param>
        /// <param name="extend"></param>
        public void Commit(string json, string extend)
        {
            T data = json.Json<T>();
            IRpcTranEvent<T, Extend> action = this._Unity.Resolve<IRpcTranEvent<T, Extend>>(this.TranName);
            if (extend.IsNull())
            {
                action.Commit(data, this._def);
                return;
            }
            else if (!this._IsBasicType)
            {
                action.Commit(data, Tools.Json<Extend>(extend));
                return;
            }
            else
            {
                Extend obj = extend.Parse(this._Type);
                action.Commit(data, obj);
            }
        }
        /// <summary>
        /// 回滚事务
        /// </summary>
        /// <param name="json">起始数据</param>
        /// <param name="extend">扩展数据</param>
        public void Rollback(string json, string extend)
        {
            T data = json.Json<T>();
            IRpcTranEvent<T, Extend> action = this._Unity.Resolve<IRpcTranEvent<T, Extend>>(this.TranName);
            if (extend.IsNull())
            {
                action.Rollback(data, this._def);
                return;
            }
            else if (!this._IsBasicType)
            {
                action.Rollback(data, Tools.Json<Extend>(extend));
                return;
            }
            else
            {
                Extend obj = extend.Parse(this._Type);
                action.Rollback(data, obj);
            }
        }
    }
}
